package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result handlerException(SQLIntegrityConstraintViolationException exception) {
        log.info(exception.getMessage(), exception);
        if (exception.getMessage().contains("Duplicate entry")) {
            String errorMsg = exception.getMessage().split(" ")[2];
            return Result.error(errorMsg.replace("'", "")+"已存在");
        }
        return Result.error("对不起,服务器出现异常,请稍后重试");
    }


    @ExceptionHandler(CustomException.class)
    public Result handlerException(CustomException exception) {
        return Result.error(exception.getMessage());
    }
}
